package com.mycat.tencent.util;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @desc 微信支付至【随机字符串】生成工具
 * @author roger
 * @date 2016年9月26日
 */
public class Utils {

    private static final String RANDOM_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    private static final Random RANDOM = new Random();

    /**
     * 生成随机字符串
     *
     * @return 随机字符串
     */
    public static String createSonceStr() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 16; i++) {
            sb.append(RANDOM_STR.charAt(RANDOM.nextInt(RANDOM_STR.length())));
        }
        return sb.toString();
    }

    /**
     * 将Map转换为XML格式字符串
     *
     * @param params
     * @return
     */
    public static String toXmlStr(Map<String, Object> params) {
        StringBuilder requestParams = new StringBuilder("<xml>");
        for (Map.Entry<String, Object> para : params.entrySet()) {
            requestParams.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey()));
        }
        requestParams.append("</xml>");
        return requestParams.toString();
    }

    /**
     * 将Map转换为XML格式字符串
     *
     * @param params
     * @return
     */
    public static String toRequestStr(Map<String, Object> params) {
        StringBuilder requestParams = new StringBuilder();
        int i = 0;
        for (Map.Entry<String, Object> para : params.entrySet()) {
            requestParams.append(String.format("%s=%s", para.getKey(), para.getValue()));
            if (i != params.size() - 1) {
                requestParams.append("&");
            }
            i++;
        }
        return requestParams.toString();
    }

    /**
     * 将微信回调xml参数转化为Map
     * @param request HttpServletRequest
     * @return Map<String, String>
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
	public static Map<String, String> parseMap(HttpServletRequest request)
            throws Exception {
        // 解析结果存储在HashMap
        Map<String, String> map = new HashMap<>();
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());

        // 释放资源
        inputStream.close();

        return map;
    }
}
